package org.metis4j.framework.mvc.impl;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.metis4j.framework.mvc.ActionHelper;
import org.metis4j.framework.mvc.Handler;
import org.metis4j.framework.mvc.HandlerMapping;
import org.metis4j.framework.mvc.bean.RequestBean;

public class DefaultHandlerMapping implements HandlerMapping {

	@Override
	public Handler getHandler(String currentRequestMethod, String currentRequestPath) {
		// TODO Auto-generated method stub
		Handler handler=null;
		Map<RequestBean, Handler> actionMap = ActionHelper.getActionMap();
		for (Map.Entry<RequestBean, Handler> actionEntry : actionMap.entrySet()) {
			RequestBean requestBean=actionEntry.getKey();
			String requestMethod=requestBean.getRequestMethod();
			String requestPath=requestBean.getRequestPath();
			Matcher matcher=Pattern.compile(requestPath).matcher(currentRequestPath);
			if(requestMethod.equalsIgnoreCase(currentRequestMethod)&&matcher.matches()){
				handler=actionEntry.getValue();
				if(handler!=null){
					handler.setRequestPathMatcher(matcher);
				}
				break;
			}
		}
		return handler;
	}

}
